package com.ruowei.modules.foodOrder.web.rest;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.group.GroupBy;
import com.querydsl.core.types.Projections;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ruowei.common.error.exception.CommonException;
import com.ruowei.common.lang.StringUtils;
import com.ruowei.modules.foodOrder.domain.*;
import com.ruowei.modules.foodOrder.domain.enumeration.OrderStatus;
import com.ruowei.modules.foodOrder.pojo.dto.OrderItemDTO;
import com.ruowei.modules.foodOrder.pojo.dto.OrderListDTO;
import com.ruowei.modules.foodOrder.repository.*;
import com.ruowei.modules.foodOrder.service.LifeCycleService;
import com.ruowei.modules.foodOrder.web.dto.CouriersDTO;
import com.ruowei.modules.sys.domain.SysUserRole;
import com.ruowei.modules.sys.domain.annotation.OrderLock;
import com.ruowei.modules.sys.domain.entity.QSysUser;
import com.ruowei.modules.sys.domain.enumeration.RoleStatusType;
import com.ruowei.modules.sys.domain.enumeration.RoleType;
import com.ruowei.modules.sys.domain.enumeration.UserStatusType;
import com.ruowei.modules.sys.domain.enumeration.UserType;
import com.ruowei.modules.sys.domain.table.SysRole;
import com.ruowei.modules.sys.domain.table.SysUserTable;
import com.ruowei.modules.sys.repository.SysRoleRepository;
import com.ruowei.modules.sys.repository.SysUserRepository;
import com.ruowei.modules.sys.repository.SysUserRoleRepository;
import com.ruowei.modules.sys.service.OperateLogService;
import com.ruowei.modules.sys.utils.CommonUtils;
import com.ruowei.modules.webSocket.domain.enumeration.MessageType;
import com.ruowei.modules.webSocket.domain.enumeration.ReceiverType;
import com.ruowei.modules.webSocket.domain.enumeration.SenderType;
import com.ruowei.modules.webSocket.service.MessagePushService;
import com.ruowei.security.CurrentUser;
import com.ruowei.security.UserModel;
import io.github.jhipster.web.util.PaginationUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.SerializationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import springfox.documentation.annotations.ApiIgnore;

import java.math.BigDecimal;
import java.time.Instant;
import java.util.*;

/**
 * REST controller for managing {@link Couriers}.
 */
@RestController
@RequestMapping("/api")
@Api(tags = "配送员相关")
@Transactional
public class CouriersResource {

    private final Logger log = LoggerFactory.getLogger(CouriersResource.class);

    private final SysRoleRepository sysRoleRepository;
    private final SysUserRoleRepository sysUserRoleRepository;
    private final SysUserRepository sysUserRepository;
    private final CouriersRepository couriersRepository;
    private final CourierOnlineLogRepository courierOnlineLogRepository;
    private final OrderRepository orderRepository;
    private final JPAQueryFactory queryFactory;
    private final PasswordEncoder passwordEncoder;
    private final MessagePushService messagePushService;
    private final LifeCycleService lifeCycleService;
    private final OperateLogService operateLogService;
    private final MerchandiseRepository merchandiseRepository;

    private final QSysUser qSysUser = QSysUser.sysUser;
    private final QCouriers qCouriers = QCouriers.couriers;
    private final QOrder qOrder = QOrder.order;
    private final QMerchant qMerchant = QMerchant.merchant;
    private final QOrderItem qOrderItem = QOrderItem.orderItem;

    public CouriersResource(SysRoleRepository sysRoleRepository, SysUserRoleRepository sysUserRoleRepository, SysUserRepository sysUserRepository, CouriersRepository couriersRepository, CourierOnlineLogRepository courierOnlineLogRepository, OrderRepository orderRepository, JPAQueryFactory queryFactory, PasswordEncoder passwordEncoder, MessagePushService messagePushService, LifeCycleService lifeCycleService, OperateLogService operateLogService, MerchandiseRepository merchandiseRepository) {
        this.sysRoleRepository = sysRoleRepository;
        this.sysUserRoleRepository = sysUserRoleRepository;
        this.sysUserRepository = sysUserRepository;
        this.couriersRepository = couriersRepository;
        this.courierOnlineLogRepository = courierOnlineLogRepository;
        this.orderRepository = orderRepository;
        this.queryFactory = queryFactory;
        this.passwordEncoder = passwordEncoder;
        this.messagePushService = messagePushService;
        this.lifeCycleService = lifeCycleService;
        this.operateLogService = operateLogService;
        this.merchandiseRepository = merchandiseRepository;
    }


    @PostMapping("/createCourier")
    @ApiOperation(value = "新增配送员接口", notes = "使用场景:web")
    public ResponseEntity<Couriers> createCourier(@RequestParam String name,
                                                  @RequestParam String sex,
                                                  @RequestParam String age,
                                                  @RequestParam String phone,
                                                  @RequestParam String password,
                                                  @RequestParam String loginCode,
                                                  @ApiIgnore @CurrentUser UserModel userModel) {
        if (couriersRepository.existsByPhone(phone)) {
            throw new CommonException("该手机号已经注册");
        }
        Couriers couriers = new Couriers();
        String courierCode = CommonUtils.getUUID();
        couriers.setCourierCode(courierCode);
        couriers.setName(name);
        couriers.setSex(sex);
        couriers.setAge(age);
        couriers.setPhone(phone);
        couriers.setAvailableStatus(true);
        couriers.setOnLineStatus(false);
        couriers.setTotalOrders(0);
        couriers.setScore(new BigDecimal(0));
        Couriers courier = couriersRepository.saveAndFlush(couriers);
        //新增用户登录
        if (sysUserRepository.existsByUserCodeAndUserTypeAndStatus(courierCode, UserType.COURIER, UserStatusType.NORMAL)) {
            throw new CommonException("不能重复添加");
        }
        //
        if (sysUserRepository.existsByLoginCodeAndStatus(loginCode, UserStatusType.NORMAL)) {
            throw new CommonException("该账号已被使用");
        }
        //更新用户表
        SysUserTable sysUser = new SysUserTable();
        sysUser.setLoginCode(loginCode);
        sysUser.setPhone(phone);
        sysUser.setUserName(couriers.getName());
        sysUser.setUserCode(courierCode);
        String encoder = passwordEncoder.encode(password);
        sysUser.setPassword(encoder);
        sysUser.setUserType(UserType.COURIER);
        sysUser.setStatus(UserStatusType.NORMAL);
        sysUserRepository.save(sysUser);
        //更新用户角色关系表
        SysRole sysRole;
        Optional<SysRole> opt = sysRoleRepository.getOneByRoleCode("ROLE_COURIER");
        if (!opt.isPresent()) {
            SysRole role = new SysRole();
            role.setIsSys(true);
            role.setRemarks("配送员角色");
            role.setRoleCode("ROLE_COURIER");
            role.setRoleName("配送员");
            role.setRoleType(RoleType.COURIER);
            role.setStatus(RoleStatusType.NORMAL);
            sysRole = sysRoleRepository.save(role);
        } else {
            sysRole = opt.get();
        }
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setSysRoleId(sysRole.getId());
        sysUserRole.setSysUserId(sysUser.getId());
        sysUserRoleRepository.save(sysUserRole);
        //添加配送员修改日志原始记录
        operateLogService.addLog(courierCode, courier.getName(), Couriers.class);

        return ResponseEntity.ok(courier);
    }


    @PostMapping("/deleteCourier/{id}")
    @ApiOperation(value = "删除配送员信息接口", notes = "使用场景:web")
    public ResponseEntity<Void> deleteCourier(@PathVariable Long id,
                                              @ApiIgnore @CurrentUser UserModel userModel) {
        Optional<Couriers> opt = couriersRepository.findById(id);
        if (!opt.isPresent()) {
            throw new CommonException("该配送员不存在");
        }
        if (opt.get().isOnLineStatus()) {
            throw new CommonException("配送员在线，无法删除");
        }
        queryFactory.update(qSysUser)
            .set(qSysUser.status, UserStatusType.DELETE)
            .where(qSysUser.userCode.eq(opt.get().getCourierCode()))
            .execute();
        couriersRepository.deleteById(id);

        return ResponseEntity.ok().build();
    }


    @PostMapping("/updateCourier/{id}")
    @ApiOperation(value = "更新配送员信息接口", notes = "使用场景:web、app")
    public ResponseEntity<Couriers> updateCourier(@PathVariable Long id,
                                                  @RequestParam(required = false) String name,
                                                  @RequestParam(required = false) String sex,
                                                  @RequestParam(required = false) String age,
                                                  @RequestParam(required = false) String phone,
                                                  @ApiIgnore @CurrentUser UserModel userModel) {
        Optional<Couriers> opt = couriersRepository.findById(id);
        if (!opt.isPresent()) {
            throw new CommonException("该配送员不存在");
        }
        if (couriersRepository.existsByPhoneAndIdNot(phone, id)) {
            throw new CommonException("该手机号已经注册");
        }
        Couriers couriers = opt.get();
        Couriers oldCouriers = SerializationUtils.clone(couriers);
        if (StringUtils.isNotEmpty(name)) {
            couriers.setName(name);
        }
        if (StringUtils.isNotEmpty(sex)) {
            couriers.setSex(sex);
        }
        if (StringUtils.isNotEmpty(age)) {
            couriers.setAge(age);
        }
        if (StringUtils.isNotEmpty(phone)) {
            if (couriers.isOnLineStatus()) {
                throw new CommonException("在线状态无法修改电话号");
            }
            queryFactory.update(qSysUser)
                .set(qSysUser.phone, phone)
                .where(qSysUser.userCode.eq(opt.get().getCourierCode()))
                .execute();
            couriers.setPhone(phone);
        }
        Couriers courier = couriersRepository.saveAndFlush(couriers);
        //添加配送员修改日志
        operateLogService.addUpdateLog(courier.getCourierCode(), courier.getName(), oldCouriers, courier);

        return ResponseEntity.ok(courier);
    }


    @PostMapping("/courierUpdatePassword/{id}")
    @ApiOperation(value = "配送员修改密码接口")
    public ResponseEntity<Void> courierUpdatePassword(@PathVariable Long id,
                                                      @RequestParam String loginCode,
                                                      @RequestParam String password,
                                                      @ApiIgnore @CurrentUser UserModel userModel) {
        Optional<Couriers> opt = couriersRepository.findById(id);
        if (!opt.isPresent()) {
            throw new CommonException("配送员不存在");
        }
        if (opt.get().isOnLineStatus()) {
            throw new CommonException("配送员在线，无法修改");
        }
        Optional<SysUserTable> sysUserOpt = sysUserRepository.findOneByUserCode(opt.get().getCourierCode());
        if (!sysUserOpt.isPresent()) {
            throw new CommonException("账号异常");
        }
        if (sysUserRepository.existsByLoginCodeAndStatusAndIdNot(loginCode, UserStatusType.NORMAL, sysUserOpt.get().getId())) {
            throw new CommonException("该账号已被使用");
        }
        //密码最低6位，数字加字母组合，区分大小写
        if (Arrays.stream(password.split("")).filter(s -> !s.equals(" ")).count() < 6) {
            throw new CommonException("密码不得少于6位数");
        }
        for (char c : password.toCharArray()) {
            if (!Character.isDigit(c) && !Character.isLetter(c)) {
                throw new CommonException("密码只能为字母和数字组合");
            }
        }
        //账号为6-20位，数字加字母组合，区分大小写
        if (Arrays.stream(loginCode.split("")).filter(s -> !s.equals(" ")).count() < 6) {
            throw new CommonException("账号不得少于6位数");
        }
        if (Arrays.stream(loginCode.split("")).filter(s -> !s.equals(" ")).count() > 20) {
            throw new CommonException("账号不得大于20位数");
        }
        for (char c : loginCode.toCharArray()) {
            if (!Character.isDigit(c) && !Character.isLetter(c)) {
                throw new CommonException("账号只能为字母和数字组合");
            }
        }
        String Encoder = passwordEncoder.encode(password);
        SysUserTable sysUser = sysUserRepository.findOneByUserCode(opt.get().getCourierCode()).orElseThrow(() -> new CommonException("账号不存在"));
        SysUserTable oldUser = SerializationUtils.clone(sysUser);
        sysUser.setLoginCode(loginCode);
        sysUser.setPassword(Encoder);
        sysUser = sysUserRepository.save(sysUser);

        operateLogService.addUpdateLog(sysUser.getUserCode(), sysUser.getUserName(), oldUser, sysUser);

        return ResponseEntity.ok().build();
    }


    @GetMapping("/getCourierList")
    @ApiOperation(value = "查询配送员信息列表接口", notes = "使用场景:web")
    public ResponseEntity<Page<CouriersDTO>> getCourierList(@RequestParam(required = false) String name,
                                                            @RequestParam(required = false) Boolean availableStatus,
                                                            @RequestParam(required = false) Boolean onLineStatus,
                                                            @ApiIgnore @CurrentUser UserModel userModel,
                                                            Pageable pageable) {
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        if (StringUtils.isNotEmpty(name)) {
            booleanBuilder.and(qCouriers.name.contains(name));
        }
        if (availableStatus != null) {
            booleanBuilder.and(qCouriers.availableStatus.eq(availableStatus));
        }
        if (onLineStatus != null) {
            booleanBuilder.and(qCouriers.onLineStatus.eq(onLineStatus));
        }
        JPAQuery<CouriersDTO> jpaQuery = queryFactory.select(Projections.bean(CouriersDTO.class, qCouriers.id, qCouriers.courierCode, qCouriers.name, qCouriers.sex,
            qCouriers.age, qCouriers.phone, qCouriers.availableStatus, qCouriers.onLineStatus, qCouriers.totalOrders, qCouriers.score, qSysUser.loginCode))
            .from(qCouriers)
            .leftJoin(qSysUser).on(qCouriers.courierCode.eq(qSysUser.userCode))
            .where(booleanBuilder)
            .orderBy(qCouriers.totalOrders.desc())
            .limit(pageable.getPageSize())
            .offset(pageable.getOffset());
        Page<CouriersDTO> page = new PageImpl<>(jpaQuery.fetch(), pageable, jpaQuery.fetchCount());
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);

        return ResponseEntity.ok().headers(headers).body(page);
    }


    @PostMapping("/courierStopEnabled/{id}")
    @ApiOperation(value = "配送员停用启用接口", notes = "使用场景:web")
    public ResponseEntity<Couriers> courierStopEnabled(@PathVariable Long id,
                                                       @RequestParam Boolean availableStatus,
                                                       @ApiIgnore @CurrentUser UserModel userModel) {
        Optional<Couriers> opt = couriersRepository.findById(id);
        if (!opt.isPresent()) {
            throw new CommonException("该配送员不存在");
        }
        if (!availableStatus && opt.get().isOnLineStatus()) {
            throw new CommonException("配送员在线，无法停用");
        }
        Couriers couriers = opt.get();
        couriers.setAvailableStatus(availableStatus);
        couriersRepository.save(couriers);

        return ResponseEntity.ok(couriers);
    }


    @PostMapping("/deliverymanOnlineOffline")
    @ApiOperation(value = "配送员上线下线接口", notes = "使用场景:app")
    public ResponseEntity<Couriers> courierOnlineOffline(@RequestParam Boolean onLineStatus,
                                                         @ApiIgnore @CurrentUser UserModel userModel) {
        Optional<Couriers> opt = couriersRepository.findOneByCourierCodeAndAvailableStatus(userModel.getUserCode(), true);
        if (!opt.isPresent()) {
            throw new CommonException("该配送员不存在");
        }
        if (!onLineStatus && !orderRepository.findAllByCourierCodeAndStatus(userModel.getUserCode(), OrderStatus.COURIER_RECEIVED).isEmpty()) {
            throw new CommonException("有未完成的订单，无法下线");
        }
        Couriers couriers = opt.get();
        couriers.setOnLineStatus(onLineStatus);
        couriersRepository.save(couriers);
        //记录日志
        CourierOnlineLog courierOnlineLog = new CourierOnlineLog();
        courierOnlineLog.setCourierCode(couriers.getCourierCode());
        courierOnlineLog.setType(onLineStatus ? "上线" : "下线");
        courierOnlineLog.setTime(Instant.now());
        courierOnlineLogRepository.save(courierOnlineLog);

        return ResponseEntity.ok(couriers);
    }


    @GetMapping("/courierGetOwnInformation")
    @ApiOperation(value = "配送员查询个人信息接口", notes = "使用场景:app")
    public ResponseEntity<Couriers> courierGetOwnInformation(@ApiIgnore @CurrentUser UserModel userModel) {
        Optional<Couriers> opt = couriersRepository.findOneByCourierCodeAndAvailableStatus(userModel.getUserCode(), true);
        if (!opt.isPresent()) {
            throw new CommonException("您的账号已停用");
        }

        return ResponseEntity.ok(opt.get());
    }


    @GetMapping("/deliverymanGetOrderList")
    @ApiOperation(value = "配送员查看订单列表接口", notes = "使用场景:app")
    public ResponseEntity<Page<OrderListDTO>> courierGetOrderList(@ApiIgnore @CurrentUser UserModel userModel,
                                                                  @RequestParam int mark,
                                                                  Pageable pageable) {
        //配送员必须为上线状态
        if (!couriersRepository.existsByCourierCodeAndAvailableStatusAndOnLineStatus(userModel.getUserCode(), true, true)) {
            List<OrderListDTO> emptyList = new ArrayList<>();
            Page<OrderListDTO> page = new PageImpl<>(emptyList, pageable, 0);
            return ResponseEntity.ok(page);
        }
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        booleanBuilder.and(qOrder.deleteStatus.eq(false));
        if (mark == 1) {
            //个人历史订单（包含未完成订单）
            booleanBuilder.and(qOrder.courierCode.eq(userModel.getUserCode()));
        } else if (mark == 2) {
            //备选订单列表
            booleanBuilder.and(qOrder.status.eq(OrderStatus.MERCHANT_RECEIVED));
        } else if (mark == 3) {
            //未完成订单
            booleanBuilder.and(qOrder.courierCode.eq(userModel.getUserCode())
                .and(qOrder.status.eq(OrderStatus.COURIER_RECEIVED)));
        } else {
            //退款流程
            booleanBuilder.and(qOrder.courierCode.eq(userModel.getUserCode()))
                .and(qOrder.status.in(OrderStatus.REFUND_APPLYING, OrderStatus.REFUND_AGREE, OrderStatus.REFUNDING, OrderStatus.REFUNDED));
        }
        List<OrderListDTO> result = new ArrayList<>(queryFactory.select(qMerchant, qOrder, qOrderItem)
            .from(qOrder)
            .leftJoin(qOrderItem).on(qOrder.orderCode.eq(qOrderItem.orderCode))
            .leftJoin(qMerchant).on(qOrder.merchantCode.eq(qMerchant.merchantCode))
            .where(booleanBuilder)
            .orderBy(qOrder.createTime.desc())
            .limit(pageable.getPageSize())
            .offset(pageable.getOffset())
            .transform(GroupBy.groupBy(qMerchant, qOrder)
                .as(Projections.bean(OrderListDTO.class, qOrder.orderCode, qOrder.createTime, qOrder.totalAmount, qOrder.payAmount, qOrder.receiverName,
                    qOrder.receiverPhone, qOrder.receiverAddress, qOrder.status, qOrder.deleteStatus, qOrder.remark,
                    qMerchant.merchantCode, qMerchant.merchantName, qMerchant.merchantAddress, qMerchant.phone, qMerchant.score,
                    GroupBy.list(Projections.bean(OrderItemDTO.class, qOrderItem.merchandiseName, qOrderItem.specification, qOrderItem.photos,
                        qOrderItem.unitPrice, qOrderItem.quantity, qOrderItem.originUnitPrice)).as("items"))))
            .values());
        long count = queryFactory.select(qOrder, qOrderItem)
            .from(qOrder)
            .where(booleanBuilder)
            .fetchCount();
        Page<OrderListDTO> page = new PageImpl<>(result, pageable, count);

        return ResponseEntity.ok(page);
    }


    @PostMapping("/courierTakeOrder")
    @ApiOperation(value = "配送员接单接口", notes = "使用场景:app")
    @OrderLock
    public ResponseEntity<HashMap<String, String>> courierTakeOrder(@RequestParam String orderCode,
                                                                    @ApiIgnore @CurrentUser UserModel userModel) {
        Optional<Couriers> couriersOptional = couriersRepository.findOneByCourierCodeAndAvailableStatus(userModel.getUserCode(), true);
        if (!couriersOptional.isPresent()) {
            throw new CommonException("您的账号已停用");
        }
        if (!couriersOptional.get().isOnLineStatus()) {
            throw new CommonException("您已下线，无法接单");
        }
        //获取order信息
        Optional<Order> opt = orderRepository.findOneByOrderCodeAndStatusAndDeleteStatus(orderCode, OrderStatus.MERCHANT_RECEIVED, false);
        if (!opt.isPresent()) {
            throw new CommonException("该订单已被处理");
        }
        Order order = opt.get();
        takeOrderSave(order, couriersOptional.get());
        Map<String, String> map = new HashMap<>();
        map.put("id", String.valueOf(order.getId()));
        map.put("orderCode", order.getOrderCode());
        map.put("status", order.getStatus().getMessage());
        //向商家推送
        messagePushService.pushMessage(SenderType.SYSTEM, userModel.getUserCode(), order.getMerchantCode(), MessageType.FOOD_ORDER, true, "配送员已接单", "已有配送员接单", map, ReceiverType.MERCHANT_APP);
        //向小程序推送
        messagePushService.pushMessage(SenderType.SYSTEM, userModel.getUserCode(), order.getMemberCode(), MessageType.FOOD_ORDER, true, "配送员接单通知", "配送员已接单", map, ReceiverType.APPLET);
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("code", "200");
        hashMap.put("msg", "抢单成功");
        return ResponseEntity.ok(hashMap);
    }


    @PostMapping("/courierCompleteOrder")
    @ApiOperation(value = "配送员完成订单接口", notes = "使用场景:app")
    @OrderLock
    public ResponseEntity<HashMap<String, String>> courierCompleteOrder(@RequestParam String orderCode,
                                                                        @ApiIgnore @CurrentUser UserModel userModel) {

        Optional<Order> opt = orderRepository.findOneByOrderCodeAndStatusAndDeleteStatus(orderCode, OrderStatus.COURIER_RECEIVED, false);
        if (!opt.isPresent()) {
            orderRepository.findOneByOrderCodeAndStatusAndDeleteStatus(orderCode, OrderStatus.DELIVERED, false).ifPresent(order -> {
                throw new CommonException("订单已送达");
            });
            throw new CommonException("订单异常，请联系管理人员");
        }

        Order order = opt.get();
        order.setStatus(OrderStatus.DELIVERED);
        order.setConfirmStatus(true);
        order.setReceiveTime(Instant.now());
        order.setUpdateTime(Instant.now());
        new Thread(() -> setSales(order)).start();

        lifeCycleService.saveLifeCycle(orderCode, null, "商品已送达", "商品已送达");
        lifeCycleService.saveLifeCycle(orderCode, null, "订单已完成", "订单已完成");

        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("code", "200");
        hashMap.put("msg", "订单已送达");
        return ResponseEntity.ok(hashMap);
    }

    /**
     * @param order
     * @apiNote 配送完成更新商品总销量
     * @author 董兴
     * @date 2020-12-03
     */
    private void setSales(Order order) {
        queryFactory.selectFrom(qOrderItem)
            .where(qOrderItem.orderCode.eq(order.getOrderCode()))
            .fetch()
            .forEach(orderItem -> {
                Optional<Merchandise> merchandiseOptional = merchandiseRepository.findFirstByMerchandiseCode(orderItem.getMerchandiseCode());
                if (merchandiseOptional.isPresent()) {
                    Merchandise merchandise = merchandiseOptional.get();
                    if (merchandise.getSale() == null) {
                        merchandise.setSale(0L);
                    }
                    //配送完成后总销量更新
                    merchandise.setSale(merchandise.getSale() + orderItem.getQuantity());
                    merchandiseRepository.saveAndFlush(merchandise);
                }
            });
    }

    public void takeOrderSave(Order order, Couriers couriers) {
        order.setStatus(OrderStatus.COURIER_RECEIVED);
        order.setCourierCode(couriers.getCourierCode());
        order.setCourierName(couriers.getName());
        order.setCourierPhone(couriers.getPhone());
        order.setCourierReceiveTime(Instant.now());
        order.setUpdateTime(Instant.now());
        orderRepository.saveAndFlush(order);
        couriers.setTotalOrders(couriers.getTotalOrders() + 1);
        couriersRepository.save(couriers);

        lifeCycleService.saveLifeCycle(order.getOrderCode(), null, "配送员已接单", "配送员已接单");
    }
}
